class Solution:
    def findLengthOfShortestSubarray(self, arr: list) -> int:
        def binary(array, left, right, num):
            while left < right:
                mid = (left + right) // 2
                if num >= array[mid]:
                    left = mid + 1
                else:
                    right = mid

            return right

        startLeft = 0
        startRight = 0
        for i in range(1, len(arr)):
            if arr[startRight] <= arr[i]:
                startRight = i
            else:
                break
        if startRight == len(arr) - 1:
            return 0
        endRight = len(arr) - 1
        endLeft = endRight
        for i in range(len(arr) - 2, -1, -1):
            if arr[endLeft] >= arr[i]:
                endLeft = i
            else:
                break
        if startLeft == startRight and endLeft == endRight:
            if arr[startLeft] <= arr[endLeft]:
                return len(arr) - 2
            else:
                return len(arr) - 1
        res = max(startRight + 1, len(arr) - endLeft)
        for i in range(endRight, endLeft - 1, -1):
            index = binary(arr, startLeft, startRight + 1, arr[i])
            res = max(res, index + len(arr) - i)
        return len(arr) - res
